from django.shortcuts import render

# Create your views here.

# 添加获取省份的视图
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView
# 缓存地址
from rest_framework.response import Response
from rest_framework_extensions.cache.mixins import CacheResponseMixin
from areas.models import Area
from areas.serializers import AreaSerializer, AddressSerializer

# 返回省信息
from users.models import Address


class AreaView(CacheResponseMixin, ListAPIView):
    # 指定查询集，获取所有省的信息
    queryset = Area.objects.filter(parent=None)
    # 指定序列化器
    serializer_class = AreaSerializer


# 返回市/区县信息（CacheResponseMixin缓存数据）
class AreasView(CacheResponseMixin, ListAPIView):
    serializer_class = AreaSerializer

    # 指定查询集，获取市/区县信息(重写)
    def get_queryset(self):
        pk = self.kwargs['pk']
        return Area.objects.filter(parent_id=pk)


# 保存信息到数据库中，并返回给前端
class AddressView(CreateAPIView, UpdateAPIView,ListAPIView):
    serializer_class = AddressSerializer

    # 更新数据（编辑）
    # queryset = Address.objects.all()

    # 查数据，返回当前用户信息（重写）
    def get_queryset(self):
        return  Address.objects.filter(user=self.request.user)

    # 删除数据
    def delete(self,request, pk):
        address = Address.objects.get(id=pk)
        address.is_deleted = True
        address.save()

        return Response({'message': 'ok'})


